package com.ruoyi.system.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import com.ruoyi.web.controller.tool.JsonResult;
import com.ruoyi.web.controller.tool.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletRequest;

/**
 * 【请填写功能名称】Controller
 * 
 * @author ruoyi
 * @date 2024-07-31
 */
@Controller
@RequestMapping("/system/renkouhecha")
public class ZhuanjiaRenkouhechaController extends BaseController
{
    private String userfilepath = "E:/userfiles/zhuanjiatetie/renkouhecha";

    private String prefix = "system/renkouhecha";

    @Autowired
    private IZhuanjiaRenkouhechaService zhuanjiaRenkouhechaService;

    @Autowired
    private IZhuanjiaRenkouhechaPiciService zhuanjiaRenkouhechaPiciService;

    @Autowired
    private IZhuanjiaDeptService zhuanjiaDeptService;

    @Autowired
    private ISysDictDataService sysDictDataService;

    @Autowired
    private IDeptService deptService;

    @RequiresPermissions("system:renkouhecha:view")
    @GetMapping()
    public String renkouhecha()
    {
        return prefix + "/renkouhecha";
    }

    /**
     * 查询【请填写功能名称】列表
     */
//    @RequiresPermissions("system:renkouhecha:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ZhuanjiaRenkouhecha zhuanjiaRenkouhecha)
    {
        startPage();
        List<ZhuanjiaRenkouhecha> list = zhuanjiaRenkouhechaService.selectZhuanjiaRenkouhechaList(zhuanjiaRenkouhecha);
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @RequiresPermissions("system:renkouhecha:export")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ZhuanjiaRenkouhecha zhuanjiaRenkouhecha)
    {
        List<ZhuanjiaRenkouhecha> list = zhuanjiaRenkouhechaService.selectZhuanjiaRenkouhechaList(zhuanjiaRenkouhecha);
        ExcelUtil<ZhuanjiaRenkouhecha> util = new ExcelUtil<ZhuanjiaRenkouhecha>(ZhuanjiaRenkouhecha.class);
        return util.exportExcel(list, "【请填写功能名称】数据");
    }

    /**
     * 新增【请填写功能名称】
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存【请填写功能名称】
     */
    @RequiresPermissions("system:renkouhecha:add")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ZhuanjiaRenkouhecha zhuanjiaRenkouhecha)
    {
        return toAjax(zhuanjiaRenkouhechaService.insertZhuanjiaRenkouhecha(zhuanjiaRenkouhecha));
    }

    /**
     * 修改【请填写功能名称】
     */
    @RequiresPermissions("system:renkouhecha:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        ZhuanjiaRenkouhecha zhuanjiaRenkouhecha = zhuanjiaRenkouhechaService.selectZhuanjiaRenkouhechaById(id);
        mmap.put("zhuanjiaRenkouhecha", zhuanjiaRenkouhecha);
        return prefix + "/edit";
    }

    /**
     * 修改保存【请填写功能名称】
     */
    @RequiresPermissions("system:renkouhecha:edit")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ZhuanjiaRenkouhecha zhuanjiaRenkouhecha)
    {
        return toAjax(zhuanjiaRenkouhechaService.updateZhuanjiaRenkouhecha(zhuanjiaRenkouhecha));
    }

    @Log(title = "专家去世确认", businessType = BusinessType.UPDATE)
    @PostMapping("/editQushi")
    @ResponseBody
    public AjaxResult editQushi(ZhuanjiaRenkouhecha zhuanjiaRenkouhecha)
    {
        ZhuanjiaRenkouhecha z = zhuanjiaRenkouhechaService.selectZhuanjiaRenkouhechaById(zhuanjiaRenkouhecha.getId());
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String datef = sdf.format(d);
        String biandong = sysDictDataService.selectDictLabel("sys_zhuanjiazhuangtai",zhuanjiaRenkouhecha.getChulijieguo());
        String str = z.getGongzuodanwei()+"于"+datef+"提交 "+z.getXingming()+" \""+biandong+"\"变动申报";

        zhuanjiaRenkouhecha.setChuliriqi(d);
        zhuanjiaRenkouhecha.setChulijieguo(str);
        return toAjax(zhuanjiaRenkouhechaService.updateZhuanjiaRenkouhecha(zhuanjiaRenkouhecha));
    }

    /**
     * 删除【请填写功能名称】
     */
    @RequiresPermissions("system:renkouhecha:remove")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(zhuanjiaRenkouhechaService.deleteZhuanjiaRenkouhechaByIds(ids));
    }

    // 解析上传的EXCEL文件
    @SuppressWarnings("resource")
    @RequestMapping("get_value")
    @ResponseBody
    public JsonResult<?> get_value(
            @RequestParam("fileurl") String mmFileUrl,
            HttpServletRequest request
    ){
        try {
            //取出文档存放的根目录，并去除文件最后的斜杠
            if(userfilepath.endsWith("/")){
                userfilepath  = userfilepath.substring(0, userfilepath.length()-1);
            }

            String url = userfilepath+mmFileUrl;
            Workbook book = null;

            File f = new File(url);
            InputStream in = new FileInputStream(f);

            String prefix = url.substring(url.lastIndexOf(".")+1);
            if(prefix.equals("xls")) {
                book = new HSSFWorkbook(in);
            }else if(prefix.equals("xlsx")) {
                book = new XSSFWorkbook(in);
            }else {
                return JsonResult.getErrorResult("请上传xls或xlsx类型的文件！");
            }

            Sheet sheet = book.getSheetAt(0);
            int column= sheet.getRow(0).getPhysicalNumberOfCells();
            int rows = sheet.getPhysicalNumberOfRows();

            List<Map<String,Object>> mmReturnList = new ArrayList<Map<String,Object>>();

            for (int i = 1; i < rows ; i++) { //行
                Map<String,Object> mmMap = new HashMap<String,Object>();
                mmMap.put("专家ID", getCellFormatValue(sheet.getRow(i).getCell(0)));
                mmMap.put("姓名", getCellFormatValue(sheet.getRow(i).getCell(1)));
                mmMap.put("单位代码", getCellFormatValue(sheet.getRow(i).getCell(2)));
                mmMap.put("所属单位", getCellFormatValue(sheet.getRow(i).getCell(3)));
                mmMap.put("工作单位", getCellFormatValue(sheet.getRow(i).getCell(4)));
                mmMap.put("身份证号", getCellFormatValue(sheet.getRow(i).getCell(5)));
                mmMap.put("死亡标识", getCellFormatValue(sheet.getRow(i).getCell(6)));
                mmMap.put("死亡日期", getCellFormatValue(sheet.getRow(i).getCell(7)));
                mmMap.put("备注", getCellFormatValue(sheet.getRow(i).getCell(8)));
                mmReturnList.add(mmMap);
            }
            in.close();
            return JsonResult.getSuccessResult(mmReturnList);
        } catch (Exception e) {
            logger.error("get_value: "+e.getMessage());
            return JsonResult.getErrorResult("获取上传文件中的数据失败！");
        }
    }

    // 导入
    @RequestMapping("import")
    @ResponseBody
    public JsonResult<?> importvalue(
            @RequestParam("piciid") String ppPiciId,
            @RequestParam("zhuanjiaid") String ppZhuanjiaId,
            @RequestParam("xingming") String ppXingming,
            @RequestParam("jigoudaima") String ppJigoudaima,
            @RequestParam("suoshudanwei") String ppSuoshudanwei,
            @RequestParam("gongzuodanwei") String ppGongzuodanwei,
            @RequestParam("shenfenzhenghao") String ppShenfenzhenghao,
            @RequestParam("siwangbiaoji") String ppSiwangbiaoji,
            @RequestParam("siwangriqi") String ppSiwangriqi,
            @RequestParam("beizhu") String ppBeizhu,
            HttpServletRequest request
    ){
        try {
            //
            ZhuanjiaRenkouhecha mmTemp = new ZhuanjiaRenkouhecha();
            mmTemp.setZhuanjiaid(ppZhuanjiaId);
            mmTemp.setShifouchuli((long)0);
            List<ZhuanjiaRenkouhecha> mmTempList = zhuanjiaRenkouhechaService.selectZhuanjiaRenkouhechaList(mmTemp);
            if(mmTempList.size()>0) {
                return JsonResult.getErrorResult("专家"+ppXingming+"已有未处理的核查信息！请检查修改后重新导入该数据！");
            }else {

                ZhuanjiaRenkouhecha mmZhuanjiaRenkouhecha = new ZhuanjiaRenkouhecha();
                mmZhuanjiaRenkouhecha.setId(UUID.randomUUID().toString());
                mmZhuanjiaRenkouhecha.setZhuanjiaid(ppZhuanjiaId);
                mmZhuanjiaRenkouhecha.setXingming(ppXingming);

                ZhuanjiaDept mmZhuanjiaDept = zhuanjiaDeptService.findByZhuanjiaId(ppZhuanjiaId);
                if (mmZhuanjiaDept==null){
                    return JsonResult.getErrorResult("查询专家出错！");
                }

                mmZhuanjiaRenkouhecha.setPiciid(ppPiciId);
                mmZhuanjiaRenkouhecha.setJigoudaima(mmZhuanjiaDept.getDeptid());
                mmZhuanjiaRenkouhecha.setSuoshudanwei(deptService.selectDeptByDeptid(mmZhuanjiaDept.getDeptid()).getDeptname());
                mmZhuanjiaRenkouhecha.setYijidanweiid(ppJigoudaima);
                mmZhuanjiaRenkouhecha.setYijidanweimingcheng(ppSuoshudanwei);
                mmZhuanjiaRenkouhecha.setGongzuodanwei(ppGongzuodanwei);
                mmZhuanjiaRenkouhecha.setShenfenzhenghao(ppShenfenzhenghao);
                mmZhuanjiaRenkouhecha.setSiwangbiaoji(ppSiwangbiaoji);

                SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
                Date mmSiwangriqi = ft.parse(ppSiwangriqi);

                mmZhuanjiaRenkouhecha.setSiwangriqi(mmSiwangriqi);
                mmZhuanjiaRenkouhecha.setBeizhu(ppBeizhu);
                mmZhuanjiaRenkouhecha.setAddtime(new Date());
                mmZhuanjiaRenkouhecha.setShifouchuli((long)0);
                mmZhuanjiaRenkouhecha.setIsvalid((long)1);

                Zhuanjiabiandongshenbao mmBiandong = new Zhuanjiabiandongshenbao();
                String mmBiandongId = UUID.randomUUID().toString();
                mmBiandong.setShenbaoid(mmBiandongId);
                mmBiandong.setDeptid(mmZhuanjiaDept.getDeptid());
                mmBiandong.setZhuanjiaid(ppZhuanjiaId);
                mmBiandong.setXingming(ppXingming);
                mmBiandong.setBiandongleixing("6");//6：去世
                mmBiandong.setBiandongshijian(mmSiwangriqi);
                mmBiandong.setStatus(1l);

                ZhuanjiabiandongshenbaoQushi mmZhuanjiabiandongshenbaoQushi = new ZhuanjiabiandongshenbaoQushi();
                mmZhuanjiabiandongshenbaoQushi.setShenbaoid(mmBiandongId);
                mmZhuanjiabiandongshenbaoQushi.setBiandongshijian(mmSiwangriqi);

                mmZhuanjiaRenkouhecha.setBiandongid(mmBiandongId);

                ZhuanjiaRenkouhechaPici mmPici = zhuanjiaRenkouhechaPiciService.selectZhuanjiaRenkouhechaPiciById(ppPiciId);
                if (mmPici==null){
                    return JsonResult.getErrorResult("该批次不存在");
                }
                mmPici.setRenshu(mmPici.getRenshu()+1);
                mmPici.setWeihecha(mmPici.getWeihecha()+1);

//                if(zhuanjiaQushiquerenService.insertZhuanjiaQushiqueren(mmZhuanjiaQushiqueren)!=1) {
//                    return JsonResult.getErrorResult("导入错误！");
//                }



                boolean add = zhuanjiaRenkouhechaService.addCustom(mmZhuanjiaRenkouhecha,mmBiandong,mmZhuanjiabiandongshenbaoQushi,mmPici);

                return add==true?JsonResult.getSuccessResult("添加成功"):JsonResult.getErrorResult("添加失败");
            }

        } catch (Exception e) {
            logger.error("ZhuanjiaQushiquerenController -> importvalue: "+e.getMessage());
            return JsonResult.getErrorResult("导入专家去世确认名单失败！");
        }
    }

    private Object getCellFormatValue(Cell cell) {
        Object cellvalue = "";
        if (cell != null) {
            // 判断当前Cell的Type
            switch (cell.getCellType()) {
                case NUMERIC:// 如果当前Cell的Type为NUMERIC
                case FORMULA: {
                    // 判断当前的cell是否为Date
                    if (DateUtil.isCellDateFormatted(cell)) {
                        // 如果是Date类型则，转化为Data格式
                        // data格式是带时分秒的：2013-7-10 0:00:00
                        // cellvalue = cell.getDateCellValue().toLocaleString();
                        // data格式是不带带时分秒的：2013-7-10
                        Date date = cell.getDateCellValue();
                        cellvalue = date;
                    } else {// 如果是纯数字
                        //cell.setCellType(1);
                        // 取得当前Cell的数值
                        //cellvalue = String.valueOf(cell.getNumericCellValue());
                        cellvalue=cell.getStringCellValue();
                    }
                    break;
                }
                case STRING:// 如果当前Cell的Type为STRING
                    // 取得当前的Cell字符串
                    cellvalue = cell.getRichStringCellValue().getString();
                    break;
                default:// 默认的Cell值
                    cellvalue = "";
            }
        } else {
            cellvalue = "";
        }
        return cellvalue;
    }

    @PostMapping("/renkouhechalist")
    @ResponseBody
    public JsonResult<?> renkouhechalist(@RequestParam("piciid") String piciid,@RequestParam("danweimingcheng") String danweimingcheng,@RequestParam("danweicengji") String danweicengji,
                                         @RequestParam("zhuanjiaxingming") String zhuanjiaxingming,@RequestParam("gongzuodanwei") String gongzuodanwei,
                                         @RequestParam("shifouchuli") String shifouchuli,@RequestParam("chuliriqi") String chuliriqi,@RequestParam("pageindex") int pageindex,@RequestParam("pagesize") int pagesize)
    {

        try{
            List<Map<String,Object>> list = zhuanjiaRenkouhechaService.qushiListBypiciid(piciid,danweimingcheng, danweicengji,
                    zhuanjiaxingming, gongzuodanwei,
                    shifouchuli, chuliriqi, pageindex, pagesize);
            int mmCount = zhuanjiaRenkouhechaService.countqushiListBypiciid(piciid,danweimingcheng, danweicengji,
                    zhuanjiaxingming, gongzuodanwei,
                    shifouchuli, chuliriqi);

            PageInfo mmPageInfo = new PageInfo(pageindex, pagesize, mmCount);
            Map<String, Object> mmMap = new HashMap<String, Object>();
            mmMap.put("list", list);
            mmMap.put("PageInfo", mmPageInfo);
            return JsonResult.getSuccessResult(mmMap);
        } catch (Exception e) {
            return JsonResult.getErrorResult(e.getMessage());
        }
    }

    @PostMapping("/qushilist")
    @ResponseBody
    public JsonResult<?> qushilist(@RequestParam("jigoudaima") String jigoudaima,
                                   @RequestParam("danweimingcheng")String danweimingcheng,
                                   @RequestParam("danweicengji")String danweicengji,
                                   @RequestParam("zhuanjiaxingming")String zhuanjiaxingming,
                                   @RequestParam("gongzuodanwei")String gongzuodanwei,
                                   @RequestParam("shifouchuli")int shifouchuli,
                                   @RequestParam("chuliriqi")String chuliriqi,
                                   @RequestParam("pageindex")int pageindex,
                                   @RequestParam("pagesize")int pagesize)
    {

        try{
            List<Map<String,Object>> list = zhuanjiaRenkouhechaService.qushiList(jigoudaima,danweimingcheng, danweicengji,
                    zhuanjiaxingming, gongzuodanwei,
                    shifouchuli, chuliriqi, pageindex, pagesize);
            int mmCount = zhuanjiaRenkouhechaService.countqushiList(jigoudaima,danweimingcheng, danweicengji,
                    zhuanjiaxingming, gongzuodanwei,
                    shifouchuli, chuliriqi);

            PageInfo mmPageInfo = new PageInfo(pageindex, pagesize, mmCount);
            Map<String, Object> mmMap = new HashMap<String, Object>();
            mmMap.put("list", list);
            mmMap.put("PageInfo", mmPageInfo);
            return JsonResult.getSuccessResult(mmMap);
        } catch (Exception e) {
            return JsonResult.getErrorResult(e.getMessage());
        }
    }

}
